﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Inbound;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Inbound
{
    public class AddInboundDetailsHandler : IRequestHandler<AddInboundDetailsCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;
        private readonly ILogger<AddInboundDetailsHandler> logger;

        public AddInboundDetailsHandler(DatabaseContext db,IMapper mapper,ILogger<AddInboundDetailsHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddInboundDetailsCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var model = mapper.Map<InboundModel>(request);
            int r=await db.SqlSugar.Insertable(model).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "库存盘点入库添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "库存盘点入库添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
